import 'package:dio/dio.dart';
import 'package:flutter_common_fragement/common/base/exception/dio_exception.dart';
import 'package:flutter_common_fragement/common/config/http_config.dart';

import '../../common/utils/index.dart';

class TokenInterceptors extends InterceptorsWrapper {
  final CancelToken _cancelToken;

  TokenInterceptors(this._cancelToken);

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    /// cancelToken
    options.cancelToken = _cancelToken;

    /// token注入
    // const token = 'token';
    options.headers["Authorization"] =
        'Bearer b5243de7ced84b6296d6b5592c3a0ddf';

    Log.d('''

请求方法:${options.method}
请求baseUrl:${options.baseUrl}
请求url:${options.path}
请求头header:${options.headers.toString()}
请求参数:${options.method == "GET" ? options.queryParameters.toString() : options.data.toString()}
''');

    return handler.next(options);
  }

  /// 按照返回的code判断（这是根据与后台沟通的业务分类的问题）
  ///  0 -> 成功
  ///  401，402 -> 未登录或者未鉴权成功
  ///  其他 -> 直接当作5xx错误抛出（内容如何，具体分析）
  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) {
    Log.d('==== Response data ====\n$response');
    final int code = response.data['code'] ?? 9999;
    if (code == HttpConfig.successCode) {
      return super.onResponse(response, handler);
    } else if (HttpConfig.refreshTokenCodes.contains(code)) {
      return handler.reject(DioUnAuthorizedError(
        requestOptions: response.requestOptions,
        error: response.data['msg'] ?? '个人信息已过期，请重新登录',
      ));
    } else {
      return handler.reject(DioResponseError(
          requestOptions: response.requestOptions,
          error: response.data['msg'] ?? "系统出现问题，请及时排查并且联系管理员"));
    }
  }

  /// 这就是dio http 自己的问题 连不上网 域名问题等～
  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    Log.e("==== Response err ====\n$err");
    return handler.reject(
        DioHttpError(requestOptions: err.requestOptions, error: err.message));
  }
}
